using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Permissions;
using System.Text;
using Microsoft.AspNetCore.Http;

namespace QQZiFramework.Mvc
{


    public class SessionIDManager
    {
        /// <summary>
        /// 强制使用token模式（请求地址的SessionId）
        /// </summary>
        public static bool WEBAPP_TokenModel = false;
        static SessionIDManager instance;

        public static SessionIDManager GetInstance()
        {
            if (instance == null) instance = new SessionIDManager();
            return instance;
        }



        private bool useRequestToken(HttpContext context)
        {
            return true;
            // bool fromReq = HtmlHelpers.IsApp(context.Request);
            // if (!fromReq)
            // {
            //     if (WEBAPP_TokenModel && (context.Request.Cookies == null || context.Request.Params["sessionId"] != null || context.Request.Params[Mvc.WebHostMemberShip.APP_TOKEN_NAME] != null))
            //     {
            //         fromReq = true;
            //     }
            // }
            // else
            // {
            //     if (context.Request.Params["sessionId"] == null && context.Request.Params[Mvc.WebHostMemberShip.APP_TOKEN_NAME] == null) fromReq = false;
            // }
            // return fromReq;
        }


        //
        // ISessionIDManager.GetSessionID
        //

        public string CreateOrGetSessionID(DBContext context)
        {
            HttpContext http = context.GetHttpContext();
            string sessionId = FromRequest(context);
            if (sessionId == null)
            {
                sessionId = Utility.Encrypt("qqzi" + Guid.NewGuid().ToString(), true);               
            }
            return sessionId;

        }

        //
        // ISessionIDManager.CreateSessionID
        //


        public string FromRequest(DBContext dbcontext)
        {
            HttpContext http = dbcontext.GetHttpContext();
            string sessionId = null;
            sessionId = dbcontext.GetArgument<string>("sessionId");
            if (sessionId != null) return sessionId;

            if (http.Request.Headers.ContainsKey("QQZI-SessionId")) sessionId = http.Request.Headers["QQZI-SessionId"];
            if (sessionId == null && http.Request.Headers.ContainsKey("qqzi_sessionId"))
            {
                sessionId = http.Request.Headers["qqzi_sessionId"];
            }
            if (sessionId == null)
            {
                sessionId = http.Request.Query["sessionId"];
                if (string.IsNullOrEmpty(sessionId))
                {
                    string token = http.Request.Query[WebHostMemberShip.APP_TOKEN_NAME];
                    return token;
                }
                else
                {
                    if (sessionId != null && sessionId.Length > 48)
                    {
                        sessionId = System.Web.HttpUtility.UrlEncode(sessionId);
                    }
                }
            }
            if (sessionId == null) return null;
            //校验是否合法
            if (sessionId.Length > 48)//早期的guid 36位
            {
                try
                {
                    string str = System.Web.HttpUtility.UrlDecode(sessionId);
                    sessionId = Utility.Decrypt(str);
                }
                catch (Exception ex)
                {
                    if (dbcontext != null) dbcontext.LogException(ex);
                    throw new Exception("SessionID：" + sessionId + " 解密异常");
                }
                if (sessionId.Substring(0, 4) != "qqzi") throw new NotAlowAccessException();

            }
            if (dbcontext != null) dbcontext.SetArgument("sessionId", sessionId);
            return sessionId;

        }
    }
}
